﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
//using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.Xml;

namespace BankingSystem.DAL
{
    public interface IEntity
    {
        string Id { get; }
    }
    public class Repository<T>
    where T : IEntity
    {
		//private Dictionary<string, T > local = new Dictionary<string,T>();
		private SerializableDictionary<string, T> local = new SerializableDictionary<string, T>();
		private BinaryFormatter formatter = new BinaryFormatter();

        public Repository()
        {
            
        }
        public void Insert(T entity) {
            local.Add(entity.Id, entity);
        }
        public void Update(T entity) { }
        public void Delete(T entity) { }
        public T ReadByld(string Id)
        {
            return local[Id];
        }

        public IList<T> CheckOut()
        {
			/*
            using (Stream s = File.OpenRead("db.dat"))
            {
                local  = (Dictionary<string, T>)formatter.Deserialize(s);
            }
			*/

			XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<string, T>));
			using (FileStream fs = new FileStream("db.xml", FileMode.Open, FileAccess.Read))
			{	
				XmlReader reader = new XmlTextReader(fs);
				local = (SerializableDictionary<string, T>)serializer.Deserialize(reader);
			}

			return local.Values.ToList();
        }

		public void SaveXML()
		{
			// Soap не работает с дженериками
			//SoapFormatter sf = new SoapFormatter();
			//using (FileStream fs = new FileStream("db.xml", FileMode.Create, FileAccess.Write))
			//{
			//	sf.Serialize(s, local);
			//}
			XmlSerializer ser = new XmlSerializer(typeof(SerializableDictionary<string, T>));
			using (FileStream fs = new FileStream("db.xml", FileMode.Create, FileAccess.Write))
			{
				ser.Serialize(fs, local);
			}
		}

        public void Save()
        {           
            using (Stream s = File.Create("db.dat"))
            {
                formatter.Serialize(s, local);
            }
       
        }
    }
}
